import time
import datetime
from config import prometheus_server


class Prometheus:
    def __init__(self, data):
        self.data = data
        self.format_data = None
        self.timestamp = int(datetime.datetime.now().timestamp())

    def markddown_data(self):
        status = "# Status\n status = {}\n".format(self.data['status'])
        labels = """# Lables\n\n"""
        annotations = "# Annotations\n\n"
        durations = "# Durations\n\n"

        for k,v in self.data['labels'].items():
            label = '{} = '.format(k)  + '{}\n\n'.format(v)
            labels += label

        for k,v in self.data['annotations'].items():
            annotation = '{} = '.format(k) + '{}\n\n'.format(v)
            annotations += annotation

        generator_url = self._generatorurl()
        source = "[Source]({})\n\n".format(generator_url)

        result = self._duration()
        d = result['duration']
        starts_at = result['starts_at']
        day, hour, minutes, seconds = d
        starts_at = "starts_at = {}\n\n".format(starts_at)
        duration = "duration = " + "{}day {}hour {}minutes {}seconds\n\n".format(day, hour, minutes, seconds)
        durations = durations + starts_at + duration

        title = self.data['labels']['alertname'] + '({})'.format(self.data['labels']['severity'])
        text = status + labels + annotations + source + durations

        self.format_data = {'title': title, 'text': text}

    def _generatorurl(self):
        url_path = self.data['generatorURL'].split('/',3)[-1]
        generator_url = prometheus_server + url_path
        return generator_url

    def _duration(self):
        eight_hour_format_seconds = 8 * 60 * 60
        d = datetime.datetime.strptime(self.data['startsAt'], "%Y-%m-%dT%H:%M:%S.%fZ")
        t = d.timetuple()
        starts_at_timestamp = int(time.mktime(t)) + eight_hour_format_seconds

        dt = datetime.datetime.utcfromtimestamp(starts_at_timestamp)
        dt = dt + datetime.timedelta(hours=8)

        duration = self.timestamp - starts_at_timestamp
        tmp, seconds = divmod(duration, 60)
        tmp, minutes = divmod(tmp, 60)
        days, hours = divmod(tmp, 24)

        return {"duration": (days, hours, minutes, seconds), "starts_at": dt}
